import React, { useState } from 'react';
import {
  Card,
  Table,
  Tag,
  Space,
  Button,
  Typography,
  Modal,
  Descriptions,
  message,
  Tooltip,
  Statistic
} from 'antd';
import {
  SyncOutlined,
  SendOutlined,
  FileTextOutlined,
  TeamOutlined
} from '@ant-design/icons';

const { Title, Paragraph } = Typography;

const mockPortfolios = [
  {
    key: '1',
    name: '稳健增长FOF组合',
    type: 'FOF组合',
    clientCount: 152,
    lastRebalance: '2024-01-15',
    status: 'deviation',
    deviation: 8.5
  },
  {
    key: '2',
    name: '全球科技先锋策略',
    type: '策略组合',
    clientCount: 89,
    lastRebalance: '2024-01-20',
    status: 'balanced',
    deviation: 1.2
  },
  {
    key: '3',
    name: '大类资产轮动',
    type: '策略组合',
    clientCount: 210,
    lastRebalance: '2023-12-28',
    status: 'deviation',
    deviation: 12.3
  }
];

const mockRebalancePlan = {
  summary: {
    portfolioName: '稳健增长FOF组合',
    clientCount: 152,
    estimatedTrades: 152 * 3, // 假设每个客户调3个基金
  },
  details: [
    { key: '1', fund: '华夏成长混合', currentWeight: 30, targetWeight: 25, action: '卖出' },
    { key: '2', fund: '易方达消费行业', currentWeight: 30, targetWeight: 35, action: '买入' },
    { key: '3', fund: '广发稳健增长', currentWeight: 40, targetWeight: 40, action: '不变' },
  ]
};

const STORAGE_KEY = 'portfolioRebalanceList';

const PortfolioRebalance = () => {
  const local = localStorage.getItem(STORAGE_KEY);
  const [portfolios, setPortfolios] = useState(local ? JSON.parse(local) : mockPortfolios);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedPortfolio, setSelectedPortfolio] = useState(null);

  const handleOpenModal = (record) => {
    setSelectedPortfolio(record);
    setIsModalVisible(true);
  };

  const handleExecuteRebalance = () => {
    message.loading({ content: '正在生成交易指令...', key: 'rebalance' });
    setTimeout(() => {
      message.success({ content: '调仓指令已成功下发至交易员！', key: 'rebalance', duration: 2 });
      setIsModalVisible(false);
      // 更新状态并写入localStorage
      const newPortfolios = portfolios.map(p => 
        p.key === selectedPortfolio.key 
          ? { ...p, status: 'balanced', deviation: 0, lastRebalance: new Date().toISOString().split('T')[0] } 
          : p
      );
      setPortfolios(newPortfolios);
      localStorage.setItem(STORAGE_KEY, JSON.stringify(newPortfolios));
    }, 2000);
  };

  const columns = [
    { title: '组合名称', dataIndex: 'name', key: 'name' },
    { title: '类型', dataIndex: 'type', key: 'type', render: t => <Tag color="blue">{t}</Tag> },
    { 
      title: '订阅客户数', 
      dataIndex: 'clientCount', 
      key: 'clientCount',
      render: count => <><TeamOutlined style={{marginRight: 8}}/>{count}</>
    },
    { title: '上次调仓日期', dataIndex: 'lastRebalance', key: 'lastRebalance' },
    { 
      title: '状态', 
      dataIndex: 'status', 
      key: 'status',
      render: (status, record) => (
        <Tag color={status === 'deviation' ? 'warning' : 'success'}>
          {status === 'deviation' ? `偏离度: ${record.deviation}%` : '已平衡'}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button
          type="primary"
          icon={<SyncOutlined />}
          onClick={() => handleOpenModal(record)}
          disabled={record.status !== 'deviation'}
        >
          发起调仓
        </Button>
      ),
    },
  ];
  
  const planColumns = [
    { title: '基金名称', dataIndex: 'fund', key: 'fund' },
    { title: '当前权重(%)', dataIndex: 'currentWeight', key: 'currentWeight' },
    { title: '目标权重(%)', dataIndex: 'targetWeight', key: 'targetWeight' },
    { title: '操作建议', dataIndex: 'action', key: 'action', render: a => <Tag color={a === '买入' ? 'success' : a === '卖出' ? 'error' : 'default'}>{a}</Tag> },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Title level={3}>组合调仓</Title>
      <Paragraph type="secondary">
        当组合策略发生调整时，在此为所有订阅该组合的客户批量发起调仓，生成交易指令下发给交易员。
      </Paragraph>

      <Card>
        <Table
          dataSource={portfolios}
          columns={columns}
          rowKey="key"
          pagination={false}
        />
      </Card>

      <Modal
        title={
            <div style={{display: 'flex', alignItems: 'center'}}>
                <FileTextOutlined style={{marginRight: 8}}/>
                <span>调仓计划审核</span>
            </div>
        }
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        width={800}
        footer={[
          <Button key="back" onClick={() => setIsModalVisible(false)}>
            取消
          </Button>,
          <Tooltip title="将为所有订阅客户生成交易指令" key="tooltip">
            <Button key="submit" type="primary" icon={<SendOutlined />} onClick={handleExecuteRebalance}>
              提交调仓计划
            </Button>
          </Tooltip>,
        ]}
      >
        {selectedPortfolio && (
            <>
                <Descriptions bordered column={2} style={{marginBottom: 24}}>
                    <Descriptions.Item label="组合名称">{mockRebalancePlan.summary.portfolioName}</Descriptions.Item>
                    <Descriptions.Item label="订阅客户数">{mockRebalancePlan.summary.clientCount}</Descriptions.Item>
                    <Descriptions.Item label="预计生成交易单" span={2}>
                        <Statistic value={mockRebalancePlan.summary.estimatedTrades} suffix="笔"/>
                    </Descriptions.Item>
                </Descriptions>
                <Title level={5}>调仓明细</Title>
                <Table
                    dataSource={mockRebalancePlan.details}
                    columns={planColumns}
                    rowKey="key"
                    pagination={false}
                    size="small"
                />
            </>
        )}
      </Modal>
    </div>
  );
};

export default PortfolioRebalance;